package com.example.picturebacked.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.picturebacked.config.CosClientConfig;
import com.example.picturebacked.manager.CosManager;
import com.example.picturebacked.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Autheor LBT
 * 模板方法进行优化文件上传（在使用普通上传以及URL上传时，通过调用公共的代码进行简化）
 */
@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;


    /**
     * 模板方法定义上传流程
     *
     * @param inputSource      上传的文件/URL
     * @param uploadPathPrefix 上传路径前缀
     */
    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 检验图片
        vaildPicture(inputSource);
        // 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = getOriginalFilename(inputSource);
        // 获取传入的真实文件名，并加入时间戳以及uuid组成上传的文件名
        String uploadPathname = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadPathname);
        File temp = null;

        try {

            temp = File.createTempFile(uploadPath, null);

            processFile(inputSource, temp);

            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, temp);

            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 获取使用数据万象处理图片信息的处理结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            // 获取图片列表信息
            List<CIObject> objectList = processResults.getObjectList();
            // 如果说不为空，则表示有处理结果
            if (CollUtil.isNotEmpty(objectList)) {
                // 如果有结果，则获取第一个处理对象(文件名修改为.webp后缀的列表)
                CIObject compressedCiObject = objectList.get(0);
                // 如果有结果，获取第二个处理方法的对象（图片进行缩略为128*128）的图片结果
                CIObject thumbnailCiObject = objectList.get(1);

                return buildResult(originalFilename, compressedCiObject, thumbnailCiObject, imageInfo);
            }
            UploadPictureResult uploadPictureResult = buildResult(imageInfo, uploadPath, originalFilename, temp);

            return uploadPictureResult;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            extracted(temp, uploadPath);
        }
    }

    private UploadPictureResult buildResult(ImageInfo imageInfo, String uploadPath, String originalFilename, File temp) {
        int width = imageInfo.getWidth();
        int height = imageInfo.getHeight();
        String format = imageInfo.getFormat();
        double picScale = NumberUtil.round((width * 1.0) / height, 2).doubleValue();
        UploadPictureResult uploadPictureResult = new UploadPictureResult();

        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(temp));
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(format);
        uploadPictureResult.setPicColor(imageInfo.getAve());
        return uploadPictureResult;
    }

    private UploadPictureResult buildResult(String originalFilename, CIObject compressedCiObject,
                                            CIObject thumbnailCiObject, ImageInfo imageInfo) {
        int width = compressedCiObject.getWidth();
        int height = compressedCiObject.getHeight();
        String format = compressedCiObject.getFormat();
        double picScale = NumberUtil.round((width * 1.0) / height, 2).doubleValue();
        UploadPictureResult uploadPictureResult = new UploadPictureResult();

        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(format);
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 设置图片为压缩后的地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadPictureResult;
    }

    /**
     * 处理输入源并生成本地临时文件
     *
     * @param temp
     */
    protected abstract void processFile(Object inputSource, File temp) throws Exception;

    /**
     * 获取输入源的原始文件名
     *
     * @param inputSource
     * @return
     */
    protected abstract String getOriginalFilename(Object inputSource);

    /**
     * 检验输入源（本地文件或者URL）
     *
     * @param inputSource
     */
    protected abstract void vaildPicture(Object inputSource);

    /**
     * 清理临时文件
     *
     * @param temp       临时文件名
     * @param uploadPath 临时文件路径
     */
    public static void extracted(File temp, String uploadPath) {
        // 删除临时文件
        if (temp != null) {
            boolean del = FileUtil.del(temp);
            if (!del) {
                log.error("删除临时文件失败 filePath={}", uploadPath);
            }
        }
    }
}























